package com.coocaa.internship.service.serviceImpl;

import com.coocaa.internship.common.ResultCode;
import com.coocaa.internship.common.ResultData;
import com.coocaa.internship.dao.UserInfoDao;
import com.coocaa.internship.pojo.UserInfo;
import com.coocaa.internship.service.UserInfoService;
import com.coocaa.internship.util.ParamvalidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 用户信息业务实现类
 * @Author: zwh
 * @Date: 2019-07-27
 * @Time: 15:14
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    UserLoginServiceImpl userLoginService;

    @Override
    public ResultData saveUserInfo(UserInfo userInfo) {
        //当用户存在时才可添加用户信息，否则返回用户不存在信息
        if (userLoginService.checkUserById(userInfo.getUserId())) {
            Integer result = userInfoDao.insertUserInfo(userInfo);
            if (result > 0) {
                return ResultData.success(null);
            }
            return ResultData.failed();
        }
        return ResultData.builder()
                .code(ResultCode.USERLOGIN_NOT_EXISTS.getCode())
                .message(ResultCode.USERLOGIN_NOT_EXISTS.getMessage())
                .build();
    }

    @Override
    public ResultData deleteUserInfoById(Long userId) {
        ParamvalidatorUtil.paramValidate(userId);
        Integer result = userInfoDao.deleteUserInfoById(userId);
        if (result > 0) {
            return ResultData.success(null);
        }
        return ResultData.failed();
    }

    @Override
    public ResultData searchUserInfoById(Long userId) {
        ParamvalidatorUtil.paramValidate(userId);
        UserInfo userInfo = userInfoDao.selectUserInfoById(userId);
        if (userInfo == null) {
            return ResultData.builder().code(ResultCode.USERINFO_NOT_EXISTS.getCode())
                    .message(ResultCode.USERINFO_NOT_EXISTS.getMessage()).data(null).build();
        }
        return ResultData.success(userInfo);
    }

    @Override
    public ResultData updateUserInfoById(UserInfo userInfo) {
        //当用户信息存在时，才可进行更新操作
        if (checkUserInfoById(userInfo.getUserId())) {
            Integer result = userInfoDao.updateUserInfoById(userInfo);
            if (result > 0) {
                return ResultData.success(null);
            }
            return ResultData.failed();
        }
        return ResultData.builder()
                .code(ResultCode.USERINFO_NOT_EXISTS.getCode())
                .message(ResultCode.USERINFO_NOT_EXISTS.getMessage())
                .build();
    }

    @Override
    public boolean checkUserInfoById(Long userId) {
        ParamvalidatorUtil.paramValidate(userId);
        UserInfo userInfo = userInfoDao.selectUserInfoById(userId);
        return userInfo != null;
    }

}
